﻿var filesHtml = {};
var url = new Url();
var $userId = url.GetQueryString("userId");
var $orderId = url.GetQueryString("orderId");
var serializer = new JSONSerializer();
var loanItems;
$(function () {//获取并绑定数据
    $("#verifyOpinion").attr("disabled", "disabled");
    $.getJSON("../Handler/LoanProductOrderHandler.ashx",
        { Type: 4, OrderId: $orderId, _: Math.random() },
        function (result) {
            if (result.Status) {
                updateProgress(result.Data);
                loanItems = result.Data.LoanItems;
                loadVerifyFiles(result.Data.Order.ProductTypeId);
                serializer.DeSerializeToSpan($(".orderInfo"), result.Data.Order);
                serializer.DeSerializeToSpan($(".userInfo"), result.Data.User);
                serializer.DeSerializeToSpan($(".workInfo"), result.Data.Work);
                serializer.DeSerializeToSpan($(".familyInfo"), result.Data.Family);
                serializer.DeSerializeToSpan($("#approvedInfo"), result.Data.Order);
                $("em[data-name='WorkEmail']").text(result.Data.Work.WorkEmail);
                $("em[data-name='IsHaveChildValue']").text(result.Data.Family.IsHaveChildValue);
                $("em[data-name='MaritalStatusValue']").text(result.Data.Family.MaritalStatusValue);
                $("em[data-name='HousePropertyValue']").text(result.Data.Family.HousePropertyValue);
                if (result.Data.ContractInfo) {
                    var contractInfo = result.Data.ContractInfo;
                    serializer.DeSerializeToSpan($("#contractArea"), result.Data.ContractInfo);
                    $("span[data-name='StartDate']").text(ChangeDateFormat(contractInfo.StartDate));
                    $("span[data-name='EndDate']").text(ChangeDateFormat(contractInfo.EndDate));
                    $("span[data-name='SignDate']").text(ChangeDateFormat(contractInfo.SignDate));
                }

                if (result.Data.Order.IsAgencyContract == 1) {
                    $("div.orgBankInfo").css("display", "block");
                    //查询机构信息
                    $("span[data-name='OrganizationName']").text(result.Data.Organization.Name);
                    $("span[data-name='OrgBankName']").text(result.Data.Organization.BankName);
                    $("span[data-name='OrgBankBranch']").text(result.Data.Organization.BankBranch);
                    $("span[data-name='OrgBankAccount']").text(result.Data.Organization.BankAccount);
                }

                //根据月还款额判断是否存在批核信息
                var repayPerMonth = $("span[data-name=RepayPerMonth]").text();
                if (repayPerMonth == "") {
                    $(".li3").css("display", "none");
                }
                else {
                    //单独绑定是否更换产品名称
                    $("div.isAccordanceProduct>span").text(result.Data.Order.IsAccordanceProduct ? "是" : "否");
                    if (result.Data.Order.IsAccordanceProduct) {
                        $("div.accordanceProduct").css("display", "block")
                            .children("span").text(result.Data.Order.ChangeProductName.split(',')[0]);
                    }

                    //单独绑定是否联名借款
                    $("div.isCoborrowLoan>span").text(result.Data.Order.IsCoborrowLoan ? "是" : "否");
                    if (result.Data.Order.IsCoborrowLoan) {
                        $("div.coborrowLoan").css("display", "block");
                        $("div.coborrowLoan>span").text(result.Data.Order.CoborrowName.split(',')[0]);
                    }
                }
                if (result.Data.Verify.result) {
                    $.each(result.Data.Verify.result, function (index, item) {
                        if (item.Index == 2) {
                            $("#verifyOpinion").val(item.AuditOpinion);
                        }
                    });
                }
                $.each(result.Data.LoanItems, function (index, item) {
                    if (!filesHtml["content" + item.AuthId]) {
                        filesHtml["content" + item.AuthId] = "";
                    }
                    $("#FileTemplate").tmpl(item.Files).appendTo($("#fileContent"));
                    filesHtml["content" + item.AuthId] += $("#fileContent").html();
                    $("#fileContent").empty();
                });

                //借款订单是否更换产品
                if (result.Data.Order.ChangeProductName != "" && result.Data.Order.ChangeProductName != null) {

                    var str = result.Data.Order.ChangeProductName.split(',');
                    if (str.length == 2) {

                        //如果是分期贷
                        if (str[1] == 31021) {
                            $("#hidContractType").val(30);
                        }
                        else if (str[1] > 31021) {
                            $("#hidContractType").val(31);
                        } else {
                            $("#hidContractType").val(25);
                        }
                    }
                } else {
                    //是否机构签约
                    if (result.Data.Order.IsAgencyContract == 1) {
                        //如果是分期贷
                        if (result.Data.Order.ProductTypeId == 31021) {
                            $("#hidContractType").val(30);
                        }
                        else {
                            $("#hidContractType").val(31);
                        }
                    } else {
                        $("#hidContractType").val(25);
                    }
                }

                //显示合同Tab层
                $(".contract_generate").css("display", "block");
                loadContractInfo.GetDictionaryLoanTypeInfo();


            } else {
                alert(result.Message);
            }
        });

    $("#contractArea .text").change(function () {
        $(this).next("span").text("");
    });

    //报表链接
    //$(".btnLoanAgreement").attr("href", "Rep_Loan_LoanAgreement.aspx?OrderId=" + $orderId);
    //$(".btnCreditAgreement").attr("href", "Rep_Loan_CreditAgreement.aspx?OrderId=" + $orderId);
    //$(".btnDebitAuth").attr("href", "Rep_Loan_DebitAuth.aspx?OrderId=" + $orderId);
    //$(".btnRepayReminder").attr("href", "Rep_Loan_RepayReminder.aspx?OrderId=" + $orderId);

    function getFormData() {
        return [{ name: "type", value: 6 }, { name: "OrderId", value: $orderId }];
    }
    //上传
    $(".btn_upload").click(function () { $("#fileupload").click() });
    $("#fileupload").fileupload({
        dataType: "json",
        limitMultiFileUploadSizeOverhead: 512,
        sequentialUploads: true,
        formData: getFormData,
        add: function (e, data) {
            if (!validateFile(data.files)) {
                return false;
            }
            $.each(data.files, function (index, file) {
                var object = [{ Name: file.name, Size: (file.size / 1024).toFixed(2), Src: getObjectURL(file) }];
                $("#uploadTemplate").tmpl(object).appendTo(".uploadlist");
            });
            data.submit();
        },
        submit: function (e, data) { $(".uploadmsg").show(); },
        progress: function (e, data) {
            var progress = parseInt(data.loaded / data.total * 100, 10);
            $(".uploadlist tr:contains(" + data.files[0].name + ") .bar").css('width', progress + '%');
            $(".uploadmsg").css("display", "block");
        },
        progressall: function (e, data) {
            var progress = parseInt(data.loaded / data.total * 100, 10);
            $("#totalbar").css('width', progress + '%');
        },
        done: function (e, data) {
            if (data.result.Status) {
                $("#completeTemplate").tmpl(data.result.Data).appendTo(".completelist");
                bindDeleteFileEvent();
                $(".submit").show();
                $.each(data.files, function (index, file) {
                    $(".uploadlist tr:contains(" + file.name + ") td:eq(4)").html("已完成");
                    $(".uploadlist tr:contains(" + file.name + ") td:last").empty();
                });
            } else {
                alert(data.result.Data.Message);
            }
        },
        stop: function (e, data) {
            $(".uploadlist").empty();
            $("#totalbar").css('width', '0%');
            $(".uploadmsg").hide();
            $(".progressBar").text("100%").css("width", "100%");
        }
    });

    //提交合同
    $(".save_c1_wai .submit").click(function () {
        if ($(".completelist tr").length == 0) {
            alert("您还没有上传任何文件！");
            return;
        }
        $.ajax({
            type: "post",
            url: "../Handler/LoanProductOrderHandler.ashx",
            dataType: "json",
            async: true,
            data: {
                type: 21,
                OrderId: $orderId
            },
            cache: false,
            complete: function () {
            },
            success: function (result) {
                alert(result.Message);
                location.href = "/View/LoanOrderList.aspx?css=1017";
            }
        });
    });

    //预加载合同文件
    var ISLOAD = false;
    $(".fileList").click(function () {
        if (!ISLOAD) {
            $.getJSON("../Handler/FileHandler.ashx", { OrderId: $orderId, type: 7, _: Math.random() }, function (result) {
                if (result == null) {
                    $(".contract_list").text("暂无相关文件！");
                }
                else if (result.length > 0) {
                    $("#contractlist").empty();
                    $.each(result, function (index, item) {
                        $("#completeTemplate").tmpl(item).appendTo(".completelist");
                        bindDeleteFileEvent();
                        //$("#contractFileTemplate").tmpl(item).appendTo($("#contractlist"));
                    });
                    // loadZoomScript();
                }
            });
            ISLOAD = true;
        }

    });

});


//添加删除图片事件 
function bindDeleteFileEvent() {
    $(".completelist").find(":button").unbind("click").click(function () {
        if (confirm("确定要删除？")) {
            var $imgId = $(this).attr("href");
            var $that = $(this);
            $.getJSON(
                "../Handler/FileHandler.ashx",
                { type: 5, FileId: $imgId, OrderId: $orderId, _: Math.random() },
                function (result) {
                    if (result.Status) {
                        $that.parents("tr").remove();
                        var count = $(".completelist tr[id]").length;
                        if (count == 0) {
                            $(".progressBar").text(50 + "%").css("width", 50 + "%");
                            $(".submit").hide();
                        }
                    }
                    else {
                        alert(result.Message);
                    }
                });
        }
    });
}



//对上传文件进行验证
function validateFile(files) {
    var result = true;
    $.each(files, function (index, file) {
        if (!/.(gif|jpg|jpeg|png|tif)$/.test(file.name.toLowerCase())) {
            alert("图片类型必须是.gif,jpeg,jpg,png,tif中的一种");
            result = false;
            return false;
        }
        if (file.size > 500 * 1024) {
            alert("文件大小不能超过500KB！");
            result = false;
            return false;
        }
    });
    return result;
}

//获取本地文件路径
function getObjectURL(file) {
    var url = null;
    if (window.createObjectURL != undefined) { // basic
        url = window.createObjectURL(file);
    } else if (window.URL != undefined) { // mozilla(firefox)
        url = window.URL.createObjectURL(file);
    } else if (window.webkitURL != undefined) { // webkit or chrome
        url = window.webkitURL.createObjectURL(file);
    }
    return url;
}

//格式化日期
function ChangeDateFormat(cellval) {
    var date = new Date(parseInt(cellval.replace("/Date(", "").replace(")/", ""), 10));
    var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
    var currentDate = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
    return date.getFullYear() + "-" + month + "-" + currentDate;
}

//更新进度条
function updateProgress(data) {
    var total = 0, count = 5;
    if (data.Order) {
        total += 100 / count;
    }
    if (data.Family) {
        total += 100 / count;
    }
    if (data.User) {
        total += 100 / count;
    }
    if (data.Work) {
        total += 100 / count;
    }
    if (data.LoanItems && data.LoanItems.length > 0) {
        total += 100 / count;
    }
    total = parseInt(total);
    $(".progressBar").text(total + "%").css("width", total + "%");
}
//加载审核文件项目
function loadVerifyFiles(productId) {
    $.getJSON("../Handler/ProductHandler.ashx",
        { Id: productId, Type: 5 },
        function (result) {
            if (result.Status) {
                $("#verifyList").empty();
                $.each(result.Data, function (index, item) {
                    $("#AuthentionTemplate").tmpl(item).appendTo("#verifyList").find(".openLayout").click(function () {
                        var authId = $(this).attr("data-authid");
                        $("#authId").val(authId);
                        $("#filelist").empty();
                        $("#filelist").html(filesHtml["content" + authId]);
                        loadZoomScript();
                    });
                });
                updateItemsStatus();
            } else {
                alert(result.Message);
            }
        });
}


//更新认证信息
function updateItemsStatus() {
    $.each(loanItems, function (index, item) {
        var dom = $("#verifyList div[data-authid='" + item.AuthId + "']");
        if (dom) {
            dom.attr("data-uploaded", true);
            if (item.Passed) {
                dom.find(".verifyStatus").text("已通过审核");
            }
            if (item.Files.length > 0) {
                dom.find(".uploadStatus").text("资料已上传");
                dom.find(".openLayout").show();
            }
        }
    });
    $("#verifyList").children("div:not('[data-uploaded]')").remove();
}
//添加预览脚本
function loadZoomScript() {
    $("#zoomScript").remove();
    $("#zoom").remove();
    var myScript = document.createElement("script");
    myScript.type = "text/javascript";
    myScript.id = "zoomScript";
    myScript.src = "../Plugins/gurdeZoom/js/zoom.min.js";
    document.body.appendChild(myScript);
}